package com.cong.juc;

import com.sun.javaws.Main;

import java.util.concurrent.*;

/**
 * 信号量 多资源《===》多个线程
 * @author cong
 * <p>
 * created on 2021/3/31 上午10:38
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8,
                0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10));

        for (int i = 1; i < 9; i++) {
            executor.execute(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"\t 获得资源");
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"等待三秒钟离开");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            });
        }
        executor.shutdown();
    }
}
